package com.lishe.lishe.lishe.module.main.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.lishe.lishe.R;
import com.lishe.lishe.asynchttp.LSWebHelper;
import com.lishe.lishe.lishe.base.BaseActivity;
import com.lishe.lishe.lishe.base.BaseApplication;
import com.lishe.lishe.lishe.common.AppManager;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.event.RefreshShopCarCountEvent;
import com.lishe.lishe.lishe.module.auth.activity.AuthActivity;
import com.lishe.lishe.lishe.module.excitation.fragment.ExcitationFragment;
import com.lishe.lishe.lishe.module.main.bean.ApkMessage;
import com.lishe.lishe.lishe.module.main.bean.NoticeObject;
import com.lishe.lishe.lishe.module.main.dialog.ShowUpdateDialog;
import com.lishe.lishe.lishe.module.main.event.TabChangeEvent;
import com.lishe.lishe.lishe.module.main.http.HttpAppUpdata;
import com.lishe.lishe.lishe.module.mall.activity.ClassifyFragment;
import com.lishe.lishe.lishe.module.mall.fragment.IndexFragment;
import com.lishe.lishe.lishe.module.mall.http.HttpMall;
import com.lishe.lishe.lishe.module.me.fragments.MineFragment;
import com.lishe.lishe.lishe.module.shopingcart.fragment.ShopCarFragment;
import com.lishe.lishe.lishe.utils.AppUtils;
import com.lishe.lishe.lishe.utils.LogUtil;
import com.lishe.lishe.lishe.utils.NetWorkUtils;
import com.lishe.lishe.lishe.utils.PermissionUtils;
import com.lishe.lishe.lishe.utils.SharedPreferencesUtils;
import com.lishe.lishe.lishe.utils.StatusBarUtil;
import com.lishe.lishe.lishe.utils.StringUtils;
import com.lishe.lishe.lishe.utils.ToastUtil;
import com.lishe.lishe.lishe.utils.Utils;
import com.lishe.lishe.retrofit.DataResponseListener;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.LinkedList;
import java.util.List;

import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.util.TextUtils;

/**
 * Created by lwa on 2017/8/9.
 * & Bin
 * 首页
 */
public class MainActivity0 extends AppCompatActivity {

    private int mCurrentPage = 0;
    private long downloadId = -1;//下载任务ID
    private DownloadManagerReceiver receiver;//下载广播监听

    private TextView mGoodsCount;
    private TabLayout mTabLayout;
    private Fragment[] mFragmensts;
    private FragmentTransaction mTransaction;

    /**
     * 从起他页面跳转到MainActivity
     */
    public static void jump(Activity activity) {
        Intent intent = new Intent(activity, MainActivity0.class);
        activity.startActivity(intent);
    }

    public static void jump(Activity activity, int page) {
        Intent intent = new Intent(activity, MainActivity0.class);
        intent.putExtra("page", page);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main0);
        AppManager.getAppManager().addActivity(this);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        mFragmensts = DataGenerator.getFragments();
        EventBus.getDefault().register(this);
        mCurrentPage = getIntent().getIntExtra("page", 0);
        initView();
        if (BaseApplication.getInstace().showUpdateDialog) {
            BaseApplication.getInstace().showUpdateDialog = false;
            getAPKNewVersion();
            //获取app通告
            getNotice();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(TabChangeEvent event) {
        LogUtil.i("index", event.getIndex() + ".....");
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mTabLayout.getTabAt(event.getIndex()).select();
            }
        }, 500);

    }

    /**
     * 获取通告
     */
    private void getNotice() {
        HttpAppUpdata.getNotice(new DataResponseListener<List<NoticeObject>>() {
            @Override
            public void onSuccess(List<NoticeObject> dataResponse) {
                if (dataResponse != null && dataResponse.size() > 0) {
                    NoticeObject notice = dataResponse.get(0);
                    String[] noticeIds = SharedPreferencesUtils.getNoticeID().split(",");
                    boolean isShow = true;
                    for (int i = 0; i < noticeIds.length; i++) {
                        if (noticeIds[i].equals(notice.getId())) {
                            isShow = false;
                            break;
                        }
                    }
                    if (isShow)
                        showNoticeDialog(notice);
                }
            }

            @Override
            public void onFail(String failMessage) {
//                toast(failMessage);
            }

            @Override
            public void onError(Throwable e) {
//                toast(R.string.network_or_server_exception);
            }
        });
    }

    private void showNoticeDialog(final NoticeObject noticeObject) {
        final Dialog dialog = new Dialog(MainActivity0.this, R.style.MyTransparentDialog);
        View view = View.inflate(MainActivity0.this, R.layout.dialog_show_notice, null);
        TextView content = view.findViewById(R.id.content);
        TextView known = view.findViewById(R.id.known);
        final ImageView dismiss = view.findViewById(R.id.dismiss);

        content.setText(noticeObject.getContent());
        known.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferencesUtils.saveNoticeID(noticeObject.getId());
                dialog.dismiss();
            }
        });

        dismiss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferencesUtils.clearNoticeID();
                dialog.dismiss();
            }
        });
        dialog.setContentView(view);
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = Utils.dip2px(MainActivity0.this, 280);
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        dialog.getWindow().setAttributes(lp);
        dialog.show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (Globals.getToken() == null) {
            mGoodsCount.setVisibility(View.GONE);
        } else {
            HttpMall.getGoodsCountFromShoppingCart(Globals.getToken(), getGoodsCountRespose);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        mCurrentPage = intent.getIntExtra("page", 0);
        setCurrentTabOrToAuth(mCurrentPage);
    }

    // Tab购物车增删实时更新底部展示ui
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(RefreshShopCarCountEvent event) {
        HttpMall.getGoodsCountFromShoppingCart(Globals.getToken(), getGoodsCountRespose);
    }

    private void initView() {
        mTabLayout = findViewById(R.id.bottom_tab_layout);
        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if ((tab.getPosition() == 2 || tab.getPosition() == 3 || tab.getPosition() == 4) && !LSWebHelper.getInstance().isUserLogined()) {
                    startActivity(new Intent(MainActivity0.this, AuthActivity.class));
                    if (mCurrentPage == 2 || mCurrentPage == 3 || mCurrentPage == 4) {
                        mTabLayout.getTabAt(0).select();
                    } else {
                        mTabLayout.getTabAt(mCurrentPage).select();
                    }
                    return;
                }
                onTabItemSelected(tab.getPosition());
                // Tab 选中之后，改变各个Tab的状态
                for (int i = 0; i < mTabLayout.getTabCount(); i++) {
                    View view = mTabLayout.getTabAt(i).getCustomView();
                    ImageView icon = view.findViewById(R.id.tab_content_image);
                    TextView text = view.findViewById(R.id.tab_content_text);
                    if (i == tab.getPosition()) { // 选中状态
                        icon.setImageResource(DataGenerator.mTabResPressed[i]);
                        text.setTextColor(getResources().getColor(R.color.color_ff4138));
                    } else {// 未选中状态
                        icon.setImageResource(DataGenerator.mTabRes[i]);
                        text.setTextColor(getResources().getColor(R.color.gray_9));
                    }
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {}

            @Override
            public void onTabReselected(TabLayout.Tab tab) {}
        });

        // 提供自定义的布局添加Tab
        for (int i = 0; i < 5; i++) {
            mTabLayout.addTab(mTabLayout.newTab().setCustomView(DataGenerator.getTabView(this, i)));
        }

        mGoodsCount = DataGenerator.getTvGoodsCount();
    }

    private void onTabItemSelected(int position) {
        int lastPage = mCurrentPage;
        //ToastUtil.showToast(MainActivity0.this, position + "...." + lastPage);
        switch (position) {
            case 0:
                mCurrentPage = 0;
                changeStatusBarColor(getResources().getColor(R.color.white));
                break;
            case 1:
                mCurrentPage = 1;
                changeStatusBarColor(getResources().getColor(R.color.white));
                break;
            case 2:
                mCurrentPage = 2;
                changeStatusBarColor(getResources().getColor(R.color.efddce));
                break;
            case 3:
                mCurrentPage = 3;
                changeStatusBarColor(getResources().getColor(R.color.white));
                break;
            case 4:
                mCurrentPage = 4;
                changeStatusBarColor(getResources().getColor(R.color.color_fd5d48));
                break;
        }

        FragmentManager mFragmentManager = getSupportFragmentManager();
        mTransaction = mFragmentManager.beginTransaction();
        // 隐藏
        mTransaction.hide(mFragmensts[lastPage]);
        // 判断是否添加
        if(!mFragmensts[mCurrentPage].isAdded()){
            mTransaction.add(R.id.home_container, mFragmensts[mCurrentPage]).show(mFragmensts[mCurrentPage]);
        }else {
            mTransaction.show(mFragmensts[mCurrentPage]);
        }
        mTransaction.commit();
        /*if (mFragmensts[mCurrentPage] != null) {
            getSupportFragmentManager().beginTransaction().replace(R.id.home_container, mFragmensts[mCurrentPage]).commit();
        }*/
    }


    /**
     * 获取商品数量
     */
    AsyncHttpResponseHandler getGoodsCountRespose = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String result = new String(responseBody);
            LogUtil.i("购物车商品数量", result);
            try {
                JSONObject json = new JSONObject(result);
                if (0 == json.optInt("errcode") && 100 == json.optInt("result")) {
                    JSONObject data = json.optJSONObject("data");
                    int num = data.optInt("num");
                    if (num > 0 && mGoodsCount != null) {
                        if (num > 999) {
                            mGoodsCount.setText("999+");
                        } else {
                            mGoodsCount.setText(num + "");
                        }
                        mGoodsCount.setVisibility(View.VISIBLE);
                    } else {
                        mGoodsCount.setVisibility(View.GONE);
                    }
                } else {
                    JSONObject msgObject = json.optJSONObject("msg");
                    String msgString = StringUtils.unicodeToString("msg", msgObject.toString());
                    LogUtil.i("商品", "" + msgString);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            ToastUtil.showToast(MainActivity0.this, R.string.network_or_server_exception);
        }
    };

    /**
     * 沉浸式颜色值修改
     */
    private void changeStatusBarColor(int color) {
        if (StatusBarUtil.setLightMode(this)) {
            StatusBarUtil.setColorNoTranslucent(this, color);
        } else {
            StatusBarUtil.setColor(this, color);
        }
    }

    /**
     * 自动登录
     *
     * @param tabIndex
     */
    public void setCurrentTabOrToAuth(int tabIndex) {
        if (LSWebHelper.getInstance().isUserLogined()) {
            mTabLayout.getTabAt(tabIndex).select();
        } else {
            startActivity(new Intent(MainActivity0.this, AuthActivity.class));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterDownloadReceiver();
        EventBus.getDefault().unregister(this);
    }

    //以下是：再返回一次退出App功能
    private static boolean isExit = false;
    Handler mExitHandler = new ExitHandler();

    static class ExitHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    }

    // 重写Activity中onKeyDown（）方法  在tab中是不响应的，
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {// 当keyCode等于退出事件值时
            ToQuitTheApp();
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();

    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
                ToQuitTheApp();
            }
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    // 封装ToQuitTheApp方法
    private void ToQuitTheApp() {
        if (isExit) {
            AppManager.getAppManager().exitApp();
        } else {
            isExit = true;
            Toast.makeText(MainActivity0.this, R.string.app_finished, Toast.LENGTH_SHORT).show();
            mExitHandler.sendEmptyMessageDelayed(0, 3000);// 3秒后发送消息
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void getAPKNewVersion() {
        HttpAppUpdata.checkApkVersion(1, new DataResponseListener<ApkMessage>() {
            @Override
            public void onSuccess(ApkMessage dataResponse) {
                checkAPKVersion(dataResponse);
            }

            @Override
            public void onFail(String failMessage) {
            }

            @Override
            public void onError(Throwable e) {
            }
        });
    }

    private void registerDownloadReceiver() {
        if (receiver == null) {
            receiver = new DownloadManagerReceiver();
        }
        IntentFilter filter = new IntentFilter();
        //点击通知action
        filter.addAction("android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED");
        //下载完成action
        filter.addAction("android.intent.action.DOWNLOAD_COMPLETE");
        registerReceiver(receiver, filter);
    }

    private void unregisterDownloadReceiver() {
        if (receiver != null) unregisterReceiver(receiver);
    }

    private void checkAPKVersion(ApkMessage dataResponse) {
        //当有新版本更新时，保存新版本的版本名和版本号
        SharedPreferencesUtils.saveAppVersionAndCode(dataResponse.getApp_version(), dataResponse.getApp_code());
        if (dataResponse.getApp_code() > AppUtils.getVersionCode(MainActivity0.this)) {
            if (dataResponse.getApp_update().equals("1") || NetWorkUtils.isWifiConnected(MainActivity0.this)) {
                registerDownloadReceiver();
                showUpdateDialog(dataResponse);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        /**
         * grantResults 返回-1，表示请求权限失败，返回0表示请求权限成功
         */
        boolean success = true;
        for (int i : grantResults) {
            if (i != 0) {
                success = false;
                break;
            }
        }
        if (success) {
            if (requestCode == PermissionUtils.request_WRITE_EXTERNAL_STORAGE && downloadId == -1) {
                downloadId = AppUtils.downLoadApkForDownloadManager(MainActivity0.this, AppUtils.APK_DOWNLOAD_URL);
            }
        } else {
            ToastUtil.showToast(MainActivity0.this, R.string.get_sdcard_permission_fail_please_to_get_permission_for_setting);
        }
    }

    private void showUpdateDialog(final ApkMessage dataResponse) {
        final ShowUpdateDialog.Builder builder = new ShowUpdateDialog.Builder(this);
        builder.setApkMessage(dataResponse);
        builder.setUpdateListener(new ShowUpdateDialog.UpdateListener() {
            @Override
            public void update() {
                if (dataResponse.getApp_update().equals("1")) {//强制更新
//                    LisheLodingActivity.jump(MainActivity0.this);
                    if (PermissionUtils.isStorageWritePermission(MainActivity0.this) && downloadId == -1) {
                        downloadId = AppUtils.downLoadApkForDownloadManager(MainActivity0.this, AppUtils.APK_DOWNLOAD_URL);
                    }
                } else {
                    if (PermissionUtils.isStorageWritePermission(MainActivity0.this) && downloadId == -1) {
                        downloadId = AppUtils.downLoadApkForDownloadManager(MainActivity0.this, AppUtils.APK_DOWNLOAD_URL);
                        builder.dissmiss();
                    }
                }
            }

            @Override
            public void dismiss() {
                if (dataResponse.getApp_update().equals("1")) {
                    exitApp();
                }
                builder.dissmiss();
            }
        });

        builder.show();
    }

    private void exitApp() {
        BaseApplication.getInstace().showUpdateDialog = true;
        AppManager.getAppManager().exitApp();
    }

}
